
package bibliotheque.server;

import bibliotheque.wave.WaveAction;
import bibliotheque.wave.WaveAgent;
import bibliotheque.wave.WaveId;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author guillaume
 */
public class PingAction extends WaveAction{
    
    private ArrayList<String> pingList;
    private String ip;
    
    public PingAction(String ip) {
        this.pingList = new ArrayList<String>();
        this.ip = ip;
    }
    
    public void PropagateBefore(WaveAgent agent) throws Exception {
        if(agent instanceof Server) {
            Server server = (Server) agent;
            server.mutex.acquireUninterruptibly();
            System.out.println(server.GetIp() + " : Ping arrived on : " + server.GetIp());
            //server.NewPing(this.wave_id);
            
            server.mutex.release();
            
        }
        
    }
    
    public void Acknowledge(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server) agent;
            server.mutex.acquireUninterruptibly();
            
            
            Iterator<String> iter = null;
            
            iter = this.pingList.iterator();
            
            while(iter.hasNext()){
                
                server.AddInPingList(this.wave_id,iter.next());
            }
            
            //server.RemovePingList(this.wave_id);
            //}
            server.mutex.release();
        }
    }
    
    public void LocalEnd(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server) agent;
            server.mutex.acquireUninterruptibly();
            
            
            //TODO : Remove for final release
            System.out.println("ADDING LocalEnd : " + server.GetIp() + "  in the List");
            //
            server.AddInPingList(this.wave_id, server.GetIp());
            
            //TODO : Remove for final release
            System.out.println(server.GetPingList(this.wave_id).toString());
            //
            
            Iterator<String> iter = server.GetPingList(this.wave_id).iterator();
            String ip;
            while(iter.hasNext()){
                ip = iter.next();
                if(!this.pingList.contains(ip))
                    this.pingList.add(ip);
            }
            server.RemovePingList(this.wave_id);
            
            server.mutex.release();
        }
    }
    
    public void GlobalEnd(WaveAgent agent) throws Exception {
        //TODO
        if (agent instanceof Server) {
            Server server = (Server) agent;
            server.mutex.acquireUninterruptibly();
            
            server.tools.get(this.ip).SetPingResult(this.pingList);
            server.RemoveTool(this.ip);
            System.out.println(this.pingList.toString());
            
            server.mutex.release();
        }
        
        
    }
    
}